package com.yinshu.teleshield.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Assert;
import com.yinshu.teleshield.domain.vo.user.LoginResult;
import com.yinshu.teleshield.domain.vo.user.LoginVO;
import com.yinshu.teleshield.jwt.ContextUserDto;
import com.yinshu.teleshield.manager.UserManager;
import com.yinshu.teleshield.tkbase.base.R;
import com.yinshu.teleshield.utils.ColumnUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import static com.yinshu.teleshield.tkbase.base.R.success;

@Tag(name = "用户登录 (User)")
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("teleshield/user/login")
public class UserLoginController {
    @Autowired
    private UserManager userManager;

    @Operation(summary = "通过手机号登录", description = "通过手机号登录")
    @PostMapping("/loginByPhone")
    public R<LoginResult> loginByPhone(@RequestBody LoginVO loginVO) {
        loginVO.verify();
        LoginResult loginResult = userManager.byPhone(loginVO.getPhone());
        return success(loginResult);
    }

    @Operation(summary = "退出登录", description = "退出登录")
    @PostMapping("/logout")
    public R<String> logout() {
        StpUtil.logout();
        return success("");
    }

    @Operation(summary = "通过token获取用户信息", description = "通过token获取用户信息")
    @GetMapping("/byToken")
    public R<LoginResult> byToken() {
        StpUtil.checkLogin();
        String phone = (String) StpUtil.getExtra(ColumnUtil.getFieldName(ContextUserDto::getPhone));
        LoginResult loginResult = userManager.byToken(phone);
        return success(loginResult);
    }
}
